package servlet;

import pojo.Dept;
import service.DeptService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


@WebServlet(urlPatterns = "/editDept")
public class DeptEditServlet extends HttpServlet {
    // alt + insert

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 3行固定代码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        // 接收参数
        String str_id = req.getParameter("id");
        // 把字符串的id转换为整数类型
        int id = Integer.parseInt(str_id);

        String dname = req.getParameter("dname");
        String manager = req.getParameter("manager");
        String str_num = req.getParameter("num");
        String createtime = req.getParameter("createtime");
        // 把字符串类型的日期转换为Date类型
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date date = simpleDateFormat.parse(createtime);

            // 创建用户对象
            Dept dept = new Dept();
            dept.setId(id);
            dept.setDname(dname);
            dept.setManager(manager);
            dept.setNum(Integer.parseInt(str_num));
            dept.setCreatetime(date);

            // 创建业务层对象
            DeptService deptService = new DeptService();
            int count = deptService.editDept(dept);

            // 判断
            if (count > 0) {
                // 重定向
                resp.sendRedirect("/dept");
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}
